<template>
  <div
    ref="tabRef"
    class="flex h-full pr-18"
    :class="[
      themeStore.tab.mode === 'chrome' ? 'items-end' : 'items-center gap-12',
    ]"
  >
    <page-tab
      v-for="item in tabStore.tabs"
      :key="item.path"
      :mode="themeStore.tab.mode"
      :dark-mode="themeStore.darkMode"
      :active="tabStore.activeTabPath === item.path"
      :active-color="themeStore.themeColor"
      :closable="item.name !== tabStore.homeTab.name"
      @click="tabStore.handleClickTab(item.path)"
      @close="tabStore.removeTab(item.path)"
      @contextmenu="handleContextMenu($event, item)"
    >
      <template #prefix>
        <icon v-if="item.meta.icon" :icon="item.meta.icon" text-16 />
      </template>
      <span relative top-1>{{ item.meta.title }}</span>
    </page-tab>
  </div>
  <context-menu
    :visible="dropdown.visible"
    :current-path="dropdown.currentPath"
    :affix="dropdown.affix"
    :x="dropdown.x"
    :y="dropdown.y"
    @update:visible="handleDropdownVisible"
  />
</template>

<script setup lang="ts">
import { PageTab } from "@soybeanjs/vue-materials";
import { useTabStore, useThemeStore } from "@/store";
import { TabRoute } from "@/store";
import { ContextMenu } from "./components";

interface Emits {
  (e: "scroll", clientX: number): void;
}
const emit = defineEmits<Emits>();

const themeStore = useThemeStore();
const tabStore = useTabStore();

// 获取当前激活的tab的clientX
const tabRef = ref();
async function getActiveTabClientX() {
  await nextTick();
  if (tabRef.value?.children?.[tabStore.activeTabIndex]) {
    const activeTabElement = tabRef.value.children[tabStore.activeTabIndex];
    const { x, width } = activeTabElement.getBoundingClientRect();
    const clientX = x + width / 2;
    setTimeout(() => {
      emit("scroll", clientX);
    }, 50);
  }
}

interface DropdownConfig {
  visible: boolean;
  affix: boolean;
  x: number;
  y: number;
  currentPath: string;
}

const dropdown: DropdownConfig = reactive({
  visible: false,
  affix: false,
  x: 0,
  y: 0,
  currentPath: "",
});

function setDropdown(config: Partial<DropdownConfig>) {
  Object.assign(dropdown, config);
}

let isClickContextMenu = false;

function handleDropdownVisible(visible: boolean) {
  if (!isClickContextMenu) {
    setDropdown({ visible });
  }
}

/** 点击右键菜单 */
const handleContextMenu = async (e: MouseEvent, tab: TabRoute) => {
  e.preventDefault();
  const { clientX, clientY } = e;
  isClickContextMenu = true;
  const DURATION = dropdown.visible ? 150 : 0;
  setDropdown({ visible: false });
  setTimeout(() => {
    setDropdown({
      visible: true,
      x: clientX,
      y: clientY,
      currentPath: tab.path,
    });

    isClickContextMenu = false;
  }, DURATION);
};

watch(
  () => tabStore.activeTabIndex,
  () => getActiveTabClientX(),
  { immediate: true }
);
</script>

<style scoped></style>
